Telegram Group & Telegram Channel
🐍 Python-задача с подвохом: “Список-призрак”

📘 Условие

Посмотри на этот код:


def append_item(item, lst=[]):
lst.append(item)
return lst

result1 = append_item(1)
result2 = append_item(2)
result3 = append_item(3)

print(result1)
print(result2)
print(result3)


Вопрос:
Что выведет программа и почему?

🔍 Варианты ответа:

А)

[1]
[2]
[3]


Б)

[1]
[1, 2]
[1, 2, 3]


В)

[3]
[3]
[3]


Правильный ответ: Б

Почему?

💥 Подвох: аргумент lst=[] — мутабельный объект, и он создаётся только один раз при определении функции, а не при каждом вызове.

📌 То есть каждый вызов append_item модифицирует один и тот же список, который "помнит" все предыдущие элементы.

Как исправить:


def append_item(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst


Теперь каждый вызов создаёт новый список, если его не передали явно.

⚠️ Подвох

• Аргументы по умолчанию вычисляются один раз
• Это работает и с dict, и с set, и с любыми объектами
• Даже опытные Python-разработчики иногда "попадаются" на этом

🎯 Отлично подходит для проверки глубокого понимания поведения функций в Python.



tg-me.com/pro_python_code/1804
Create:
Last Update:

🐍 Python-задача с подвохом: “Список-призрак”

📘 Условие

Посмотри на этот код:


def append_item(item, lst=[]):
lst.append(item)
return lst

result1 = append_item(1)
result2 = append_item(2)
result3 = append_item(3)

print(result1)
print(result2)
print(result3)


Вопрос:
Что выведет программа и почему?

🔍 Варианты ответа:

А)

[1]
[2]
[3]


Б)

[1]
[1, 2]
[1, 2, 3]


В)

[3]
[3]
[3]


Правильный ответ: Б

Почему?

💥 Подвох: аргумент lst=[] — мутабельный объект, и он создаётся только один раз при определении функции, а не при каждом вызове.

📌 То есть каждый вызов append_item модифицирует один и тот же список, который "помнит" все предыдущие элементы.

Как исправить:


def append_item(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst


Теперь каждый вызов создаёт новый список, если его не передали явно.

⚠️ Подвох

• Аргументы по умолчанию вычисляются один раз
• Это работает и с dict, и с set, и с любыми объектами
• Даже опытные Python-разработчики иногда "попадаются" на этом

🎯 Отлично подходит для проверки глубокого понимания поведения функций в Python.

BY Python RU


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/pro_python_code/1804

View MORE
Open in Telegram


Python RU Telegram | DID YOU KNOW?

Date: |

That strategy is the acquisition of a value-priced company by a growth company. Using the growth company's higher-priced stock for the acquisition can produce outsized revenue and earnings growth. Even better is the use of cash, particularly in a growth period when financial aggressiveness is accepted and even positively viewed.he key public rationale behind this strategy is synergy - the 1+1=3 view. In many cases, synergy does occur and is valuable. However, in other cases, particularly as the strategy gains popularity, it doesn't. Joining two different organizations, workforces and cultures is a challenge. Simply putting two separate organizations together necessarily creates disruptions and conflicts that can undermine both operations.

Can I mute a Telegram group?

In recent times, Telegram has gained a lot of popularity because of the controversy over WhatsApp’s new privacy policy. In January 2021, Telegram was the most downloaded app worldwide and crossed 500 million monthly active users. And with so many active users on the app, people might get messages in bulk from a group or a channel that can be a little irritating. So to get rid of the same, you can mute groups, chats, and channels on Telegram just like WhatsApp. You can mute notifications for one hour, eight hours, or two days, or you can disable notifications forever.

Python RU from sg


Telegram Python RU
FROM USA